<template>
  <div class="todo-container">
    <!-- 新建待办对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑待办' : '新建待办'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="todoForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="todoForm.title" placeholder="请输入待办事项标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="todoForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入待办事项描述"
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="todoForm.priority" placeholder="请选择优先级">
            <el-option label="低优先级" :value="0" />
            <el-option label="中优先级" :value="1" />
            <el-option label="高优先级" :value="2" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="截止日期" prop="due_date">
          <el-date-picker
            v-model="todoForm.due_date"
            type="datetime"
            placeholder="请选择截止日期"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ isEditing ? '保存' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-row :gutter="20">
      <!-- 左侧待办列表 -->
      <el-col :span="16">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待办事项</span>
              <el-button type="primary" @click="openCreateDialog">
                <el-icon><Plus /></el-icon>
                新建待办
              </el-button>
            </div>
          </template>

          <!-- 筛选器 -->
          <div class="filter-container">
            <el-select v-model="filter.priority" placeholder="优先级" clearable>
              <el-option label="低优先级" :value="0" />
              <el-option label="中优先级" :value="1" />
              <el-option label="高优先级" :value="2" />
            </el-select>
            <el-select v-model="filter.completed" placeholder="状态" clearable>
              <el-option label="未完成" :value="false" />
              <el-option label="已完成" :value="true" />
            </el-select>
          </div>

          <!-- 待办列表 -->
          <el-table :data="filteredTodos" style="width: 100%">
            <el-table-column width="50">
              <template #default="{ row }">
                <el-checkbox 
                  v-model="row.completed"
                  @change="() => toggleTodoStatus(row)"
                />
              </template>
            </el-table-column>
            
            <el-table-column prop="title" label="标题">
              <template #default="{ row }">
                <span :class="{ 'completed': row.completed }">{{ row.title }}</span>
                <div class="todo-description" v-if="row.description">
                  {{ row.description }}
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)">
                  {{ getPriorityLabel(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="due_date" label="截止日期" width="180">
              <template #default="{ row }">
                <span>{{ formatDate(row.due_date) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button 
                    type="primary" 
                    link
                    @click="editTodo(row)"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    type="danger" 
                    link
                    @click="deleteTodo(row)"
                  >
                    删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 右侧统计 -->
      <el-col :span="8">
        <el-card shadow="hover" class="stats-card">
          <template #header>
            <div class="card-header">
              <span>任务概览</span>
            </div>
          </template>
          
          <div class="stats-content">
            <div class="stat-item">
              <div class="stat-label">总任务数</div>
              <div class="stat-value">{{ todos.length }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">已完成</div>
              <div class="stat-value">{{ completedCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">待完成</div>
              <div class="stat-value">{{ pendingCount }}</div>
            </div>
            <div class="stat-item">
              <div class="stat-label">完成率</div>
              <div class="stat-value">{{ completionRate }}%</div>
            </div>
          </div>

          <el-progress 
            :percentage="completionRate"
            :status="completionRate === 100 ? 'success' : ''"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { todoApi } from '@/api/todo'

// 基础数据
const todos = ref([])
const dialogVisible = ref(false)
const isEditing = ref(false)
const formRef = ref(null)

// 表单数据
const todoForm = ref({
  title: '',
  description: '',
  priority: 0,
  due_date: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 筛选条件
const filter = ref({
  priority: null,
  completed: null
})

// 计算属性
const filteredTodos = computed(() => {
  return todos.value.filter(todo => {
    if (filter.value.priority !== null && todo.priority !== filter.value.priority) {
      return false
    }
    if (filter.value.completed !== null && todo.completed !== filter.value.completed) {
      return false
    }
    return true
  })
})

const completedCount = computed(() => {
  return todos.value.filter(todo => todo.completed).length
})

const pendingCount = computed(() => {
  return todos.value.filter(todo => !todo.completed).length
})

const completionRate = computed(() => {
  if (!todos.value.length) return 0
  return Math.round((completedCount.value / todos.value.length) * 100)
})

// 方法
const fetchTodos = async () => {
  try {
    todos.value = await todoApi.getTodos()
  } catch (error) {
    console.error('获取待办事项失败:', error)
    ElMessage.error('获取待办事项失败')
  }
}

const openCreateDialog = () => {
  isEditing.value = false
  todoForm.value = {
    title: '',
    description: '',
    priority: 0,
    due_date: ''
  }
  dialogVisible.value = true
}

const editTodo = (todo) => {
  isEditing.value = true
  todoForm.value = { ...todo }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEditing.value) {
      await todoApi.updateTodo(todoForm.value.id, todoForm.value)
      ElMessage.success('更新成功')
    } else {
      await todoApi.createTodo(todoForm.value)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchTodos()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const toggleTodoStatus = async (todo) => {
  try {
    await todoApi.updateTodo(todo.id, { completed: todo.completed })
    ElMessage.success(todo.completed ? '已完成' : '已取消完成')
  } catch (error) {
    console.error('更新状态失败:', error)
    todo.completed = !todo.completed // 恢复状态
    ElMessage.error('更新失败')
  }
}

const deleteTodo = async (todo) => {
  try {
    await ElMessageBox.confirm('确定要删除这个待办事项吗？', '提示', {
      type: 'warning'
    })
    
    await todoApi.deleteTodo(todo.id)
    ElMessage.success('删除成功')
    fetchTodos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const getPriorityType = (priority) => {
  const types = ['info', 'warning', 'danger']
  return types[priority] || 'info'
}

const getPriorityLabel = (priority) => {
  const labels = ['低', '中', '高']
  return labels[priority] || '低'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 初始化
fetchTodos()
</script>

<style scoped>
.todo-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.completed {
  text-decoration: line-through;
  color: var(--el-text-color-secondary);
}

.todo-description {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-top: 4px;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-content {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 12px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
}

.stat-label {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-col {
    width: 100% !important;
  }
  
  .stats-card {
    margin-top: 20px;
  }
}
</style> 